﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using L006_Manage.Models;

namespace L006_Manage.Controllers
{
    public class HomeController : Controller
    {
        Model1 model = new Model1();

        /// <summary>
        /// 主页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var list = model.Task.ToList();
            return View(list);
        }

        /// <summary>
        /// 详情
        /// </summary>
        /// <returns></returns>
        public ActionResult Details(int id)
        {
            Task task = model.Task.FirstOrDefault(p => p.TaskID == id);
            if (task!=null)
            {
                return View(task);
            }
            return View();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        public ActionResult Add()
        {

            return View();
        }
        [HttpPost]
        public ActionResult Add(Task task)
        {
            model.Task.Add(task);
            var result = model.SaveChanges();
            if (ModelState.IsValid)//验证
            {
                if (result > 0)
                {
                    return RedirectToAction("index");
                }
            }
            return View(task);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit(int id)
        {
            var task = model.Task.FirstOrDefault(p => p.TaskID == id);
           
            return View(task);
        }
        [HttpPost]
        public ActionResult Edit(Task task)
        {
           
           
            if (ModelState.IsValid)//验证
            {
                var n = model.Task.FirstOrDefault(p=>p.TaskID==task.TaskID);

                n.TaskPriority = task.TaskPriority;
                n.Content = task.Content;
                n.AddTime = task.AddTime;
                n.TaskState = task.TaskState;
                n.FinishedTime = task.FinishedTime;
                n.uid = task.uid;
                var result = model.SaveChanges();//保存
                if (result > 0)
                {
                    return RedirectToAction("index");
                }
            }
            return View(task);
        }
        [HttpPost]
        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        public ActionResult Delete(int id)
        {
            Task task = model.Task.FirstOrDefault(p => p.TaskID == id);

            if (task != null)
            {
                model.Task.Remove(task);
                var result = model.SaveChanges() > 0;//保存至数据库
                return Json(result);
            }
            return Json(false);
        }

    }
}